package com.aceleeyy.sevenstar.controller;

import com.aceleeyy.sevenstar.config.ErrorMessage;
import com.aceleeyy.sevenstar.config.SevenStarCommonInfo;
import com.aceleeyy.sevenstar.dao.MagazineMapper;
import com.aceleeyy.sevenstar.dao.MagazinePicturesMapper;
import com.aceleeyy.sevenstar.dao.UserInfoMapper;
import com.aceleeyy.sevenstar.model.Magazine;
import com.aceleeyy.sevenstar.model.MagazinePictures;
import com.aceleeyy.sevenstar.model.Result;
import com.aceleeyy.sevenstar.model.UserInfo;
import com.aceleeyy.sevenstar.utils.WXAuthUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户管理
 *
 * @auther: Ace Lee
 * @date: 2019/10/26 10:43
 */
@Api(value = "用户管理", description = "用户管理")
@Slf4j
@RestController
@RequestMapping("users")
public class UserInfoController extends BaseController {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private MagazineMapper magazineMapper;
    @Autowired
    private MagazinePicturesMapper magazinePicturesMapper;

    @ApiOperation(value = "杂志审核")
    @PostMapping("/{openid}/verify")
    public Result verify(HttpServletRequest request,@PathVariable String openid,@RequestBody Map<String,Object> params){
        Result result;
        log.info("杂志审核,请求开始,{},{}",openid,params);

        try {
            //审核人员
            UserInfo userInfo = getUserByOpenid(openid);
            if (null!=userInfo && userInfo.getIsValid()){
                //审核杂志
                params.put("verifyUser",userInfo.getNickname());
                params.put("verifyTime",new Date());
                int v = magazineMapper.verify(params);
                log.info("杂志审核,结果,{}",v);
            }
            result = Result.sucess();
        } catch (Exception e) {
            log.error("杂志审核,异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    @ApiOperation(value = "杂志审核信息")
    @GetMapping("/{openid}/verifies")
    public Result verifies(HttpServletRequest request,@PathVariable String openid){
        Result result;
        List<Magazine> rows = Lists.newArrayList();
        log.info("杂志审核信息的请求开始,{}",openid);

        try {
            //审核人员
            UserInfo userInfo = getUserByOpenid(openid);
            if (null!=userInfo && userInfo.getIsValid()){
                //获取待审核的杂志
                rows = magazineMapper.selectVerifyingMagazines();
                if (!CollectionUtils.isEmpty(rows)){
                    log.info("杂志审核信息查询成功：{}",rows.size());
                    rows.forEach(magazine -> {
                        List<MagazinePictures> pictures = magazinePicturesMapper.selectByMagazineId(magazine.getId());
                        magazine.setPictures(pictures);
                    });
                }
            }
            result = new Result<>(rows);
        } catch (Exception e) {
            log.error("杂志审核信息查询异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }

    @ApiOperation(value = "微信登陆")
    @GetMapping("/wxLogin")
    public Result wxLogin(HttpServletRequest request, @RequestParam String code) {
        Result result;
        log.info("登陆-请求参数：{}", code);
        if (StringUtils.isEmpty(code)) {
           return Result.error(ErrorMessage.E_001.getErrDesc());
        }

        try {
            //start 获取微信用户基本信息
            //第一步：通过code换取网页授权access_token
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAuthUtil.APPID
                    + "&secret=" + WXAuthUtil.APPSECRET
                    + "&code=" + code
                    + "&grant_type=authorization_code";

            log.info("登陆-通过code换取网页授权access_token的url:" + url);
            JSONObject jsonObject = WXAuthUtil.doGetJson(url);
            String openid = jsonObject.getString("openid");
            String access_token = jsonObject.getString("access_token");
            String refresh_token = jsonObject.getString("refresh_token");
            //第二步验证access_token是否失效；展示都不需要
            String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;

            JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
            log.info("登陆-验证access_token是否失效的结果：{}",chickuserInfo.toString());
            if (!"0".equals(chickuserInfo.getString("errcode"))) {
                // 第三步：刷新access_token（如果需要）-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki，
                String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;

                JSONObject refreshInfo = WXAuthUtil.doGetJson(refreshTokenUrl);

                log.info("登陆-刷新access_token的结果：{}",refreshInfo.toString());
                access_token = refreshInfo.getString("access_token");
            }

            // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
                    + "&openid=" + openid
                    + "&lang=zh_CN";
            log.info("登陆-拉取用户信息infoUrl:" + infoUrl);
            JSONObject userObject = WXAuthUtil.doGetJson(infoUrl);

            if (null==userObject){
                Map<String,String> map = Maps.newHashMap();
                map.put("openid",openid);
                map.put("access_token",access_token);
                log.info("登陆-结果：{}", userObject.toJSONString());
                result = new Result<>(userObject);
                return result;
            }

            //保存用户信息
            UserInfo existUser = getUserByOpenid(openid);
            if (null==existUser && !StringUtils.isEmpty(openid)){
                UserInfo userInfo = new UserInfo();
                userInfo.setCode(code);
                userInfo.setOpenid(openid);
                userInfo.setNickname(userObject.getString("nickname"));
                userInfo.setSex(userObject.getString("sex"));
                userInfo.setHeadimgurl(userObject.getString("headimgurl"));
                userInfo.setCountry(userObject.getString("country"));
                userInfo.setCity(userObject.getString("city"));
                userInfo.setProvince(userObject.getString("province"));
                userInfo.setPrivilege(String.valueOf(userObject.getJSONArray("privilege")));
                userInfo.setUnionid(null==userObject.getString("unionid")?"":userObject.getString("unionid"));
//                userInfo.setRemark(access_token);
                userInfo.setCreatedTime(new Date());
                userInfo.setIsValid(SevenStarCommonInfo.BOOLEAN_NO);
                int addUser = userInfoMapper.insertSelective(userInfo);
                log.info("登陆-保存用户结果：{}", addUser);
            }

            //返回用户openid
      /*      Map<String,String> map = Maps.newHashMap();
            map.put("openid",openid);
            map.put("access_token",access_token);*/
            log.info("登陆-结果：{}", userObject.toJSONString());
            result = new Result<>(userObject);
        } catch (Exception e) {
            log.error("登陆-异常：{}", Throwables.getStackTraceAsString(e));
            result = Result.error(ErrorMessage.E_999.getErrDesc());
        }
        return result;
    }


}
